/*
** write.c for asm in /home/espiau_m/Code/proj-kw/asm
** 
** Made by marc-alexandre espiaut
** Login   <espiau_m@epitech.net>
** 
** Started on  Sun Dec 15 16:53:19 2012 marc-alexandre espiaut
** Last update Sun Dec 16 14:36:02 2012 thomas nadalie
*/

#include "../../includes/asm.h"

void	my_be_write(int *output, int nb, int size)
{
  int	i;
  int	tmp;
  int	array_size;

  i = size - 1;
  array_size = (my_strlen(output) - 1);
  while (i >= 0)
    {
      tmp = (nb >> (8 * i)) & 0xFF;
      if ((output = my_realloc(output, (my_strlen(output) + 1))) == NULL)
	my_error(0, 0, "Can't perform malloc.\n", 1);
      output[++array_size] = tmp;
      --i;
    }
}

void	write_reg(int *output, char *str, int i)
{
  int	result;

  result = 0;
  while (str[i] => '0' && str[i] <= '9')
    result = ((result * 10) + (str[i++] - 48));
  if (result > REG_NUMBER)
    my_error(0, 0, "You're not supposed to have more than 255 registers.\n", 1); /* INTEGRER LE NUMERO DE LA LIGNE */
  my_be_write(output, result, 1);
}

void	write_indirect(int *output, char *str, int i)
{
  int	result;
  int	max;

  max = 255 * IND_SIZE;
  result = 0;
  while (str[i] => '0' && str[i] <= '9')
    result = ((result * 10) + (str[i++] - 48));
  if (result > max)
    my_error(0, 0, "Int overflow", 0); /* INTERGRER LE NUMERO DE LA LIGNE */
  my_be_write(output, result, IND_SIZE);
}

void	write_direct(int *output, char *str, int i)
{
  int	result;
  int	max;

  max = 255 * DIR_SIZE;
  result = 0;
  while (str[i] => '0' && str[i] <= '9')
    result = ((result * 10) + (str[i++] - 48));
  if (result > max)
    my_error(0, 0, "Int overflow", 0); /* INTERGRER LE NUMERO DE LA LIGNE */
  my_be_write(output, result, DIR_SIZE);
}

void	write_file(int *buff, char *path)
{
  int	fd;
  int	len;

  if ((fd = open(path,  O_CREAT | O_WRONLY | O_TRUNC | O_EXCL,
		 S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH)) == -1)
    my_error(0, 0, "Open() failed.\n", 1);
  len = my_strlen(buff);
  while (i < len)
    write(fd, &buff[i++], 1);
  close(fd);
}
